package tw.miku.protocol.codec.login;

import java.nio.charset.CharacterCodingException;
import java.util.Collection;

import org.apache.mina.core.buffer.IoBuffer;

import tw.miku.constants.ProtocalConstants;
import tw.miku.model.Room;
import tw.miku.model.User;
import tw.miku.protocol.codec.AbstractResponseMessagePack;
import tw.miku.util.BufferUtility;

public class LoginResponsePack extends AbstractResponseMessagePack
{

	public byte result;
	public int id;

	public short marjorVersion;
	public short minorVersion;

	public String name;
	public Collection<User> users;
	public Collection<Room> rooms;

	public LoginResponsePack()
	{

	}

	@Override
	public short getTag()
	{
		return ProtocalConstants.LOGIN;
	}

	@Override
	public IoBuffer encode() throws CharacterCodingException
	{
		IoBuffer buf = IoBuffer.allocate(100).setAutoExpand(true);
		buf.position(4);
		buf.putShort(getTag());
		buf.putShort((short) 0);
		if (result == 0)
		{
			buf.put(result);
			buf.putUnsignedInt(id);
			buf.putUnsignedShort(marjorVersion);
			buf.putUnsignedShort(minorVersion);
			BufferUtility.writeString(buf, name);
			BufferUtility.writeArray(buf, users);
			BufferUtility.writeArray(buf, rooms);
		}
		else
		{
			buf.put(result);
		}
		buf.flip();
		buf.putUnsignedInt(buf.limit() - 4);
		buf.position(0);
		return buf;
	}
}
